package com.itfreer.gis.server.utils.webp;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.FileImageOutputStream;

import com.luciad.imageio.webp.WebPReadParam;
import com.luciad.imageio.webp.WebPWriteParam;

public class WebpConvert {

	/**
	 * @param: srcFile
	 * @param: webpFile
	 * @description: 将文件编码为WEBP格式
	 */
	public static void encodingToWebp(String srcFile, String webpFile) {
		encodingToWebp(new File(srcFile), new File(webpFile));
	}

	/**
	 * @param: srcFile 图片
	 * @param: webpFile webp文件
	 * @description: 将文件编码为WEBP格式
	 */
	@SuppressWarnings("unused")
	public static void encodingToWebp(File srcFile, File webpFile) {
		ImageWriter writer = null;
		FileImageOutputStream fileImageOutputStream = null;
		try {
			convertWebp(srcFile, webpFile, writer, fileImageOutputStream);

			// 释放writer
			if (writer != null) {
				writer.dispose();
			}

			// 关闭文件流
			if (fileImageOutputStream != null) {
				fileImageOutputStream.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param: srcFiles 图片
	 * @param: webpFiles webp文件
	 * @param: level 文件级别，1为等级目录，2为行目录，3为列文件
	 * @description: 将文件编码为WEBP格式
	 */
	@SuppressWarnings("unused")
	public static void encodingToWebp(File[] srcFiles, File[] webpFiles, int level) {
		ImageWriter writer = null;
		FileImageOutputStream fileImageOutputStream = null;
		try {
			if (level == 1) {// 1级目录，全部转换成webp之后再进行上传
				File[] levelFiles = srcFiles;
				webpFiles = new File[levelFiles.length];
				File parentFile = srcFiles[0].getParentFile();

				for (int i = 0; i < levelFiles.length; i++) {
					File levelFile = levelFiles[i];
					File[] rowFiles = levelFile.listFiles();

					for (int j = 0; j < rowFiles.length; j++) {
						File rowFile = rowFiles[i];
						File webpRowFile = new File(
								parentFile.getPath() + "_webp" + "/" + levelFile.getName() + "/" + rowFile.getName());
						if (!webpRowFile.exists()) {// 创建新的行文件夹
							webpRowFile.mkdirs();
						}
						File[] colFiles = rowFile.listFiles();
						for (int k = 0; k < colFiles.length; k++) {
							File colFile = colFiles[i];

							// 将图片转换为webp格式
							String webpName = webpRowFile.getPath() + "/" + colFile.getName().split("\\.")[0] + ".webp";
							File webpFile = new File(webpName);
							if (!webpFile.exists()) {
								webpFile.createNewFile();
							}
							convertWebp(colFile, webpFile, writer, fileImageOutputStream);
						}
					}
					webpFiles[i] = new File(parentFile.getPath() + "_webp" + "/" + levelFile.getName());
				}
			}

			if (level == 3) {
				for (int i = 0; i < srcFiles.length; i++) {
					File srcFile = srcFiles[i];
					if (srcFile.getName().lastIndexOf(".webp") != -1) {// 如果当前文件是webp，则跳过不进行转换
						webpFiles[i] = srcFile;
						continue;
					}
					// 将图片转换为webp格式
					String webpName = srcFile.getPath().split("\\.")[0] + ".webp";
					File webpFile = new File(webpName);
					if (!webpFile.exists()) {
						webpFile.createNewFile();
					}

					convertWebp(srcFile, webpFile, writer, fileImageOutputStream);

					webpFiles[i] = webpFile;
				}
			}

			// 释放writer
			if (writer != null) {
				writer.dispose();
			}

			// 关闭文件流
			if (fileImageOutputStream != null) {
				fileImageOutputStream.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void convertWebp(File srcFile, File webpFile, ImageWriter writer,
			FileImageOutputStream fileImageOutputStream) {
		try {
			// 获取图片数据
			BufferedImage image = ImageIO.read(srcFile);
			// 获取WebP ImageWriter实例
			writer = ImageIO.getImageWritersByMIMEType("image/webp").next();

			// 配置编码参数
			WebPWriteParam writeParam = new WebPWriteParam(writer.getLocale());
			writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
			writeParam.setCompressionType(writeParam.getCompressionTypes()[WebPWriteParam.LOSSLESS_COMPRESSION]);
//			writeParam.setCompressionQuality(0.01f);// 压缩比例0-1之间

			// 配置ImageWriter上的输出
			fileImageOutputStream = new FileImageOutputStream(webpFile);
			writer.setOutput(fileImageOutputStream);

			// 进行编码转换
			writer.write(null, new IIOImage(image, null, null), writeParam);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param: webpFile
	 * @param: toFile
	 * @param: fileType 文件格式 png,jpg,jpeg
	 * @description: 将WEBP格式解码为其他文件
	 */
	public static void decodingFromWebp(String webpFile, String toFile) {
		decodingFromWebp(new File(webpFile), new File(toFile),
				toFile.substring(toFile.lastIndexOf('.') + 1, toFile.length()));
	}

	/**
	 * @param: webpFile
	 * @param: toFile
	 * @param: fileType 文件格式 png,jpg,jpeg
	 * @description: 将WEBP格式解码为其他文件
	 */
	public static void decodingFromWebp(File webpFile, File toFile, String fileType) {

		try {
			// 获取WebP ImageReader实例
			ImageReader reader = ImageIO.getImageReadersByMIMEType("image/webp").next();

			// 配置解码参数
			WebPReadParam readParam = new WebPReadParam();
			readParam.setBypassFiltering(true);

			// 配置ImageReader上的输入
			FileImageInputStream fileImageInputStream = new FileImageInputStream(webpFile);
			reader.setInput(fileImageInputStream);

			// 进行解码转换
			BufferedImage image = reader.read(0, readParam);
			ImageIO.write(image, fileType, toFile);

			// 释放reader
			reader.dispose();

			// 关闭文件流
			fileImageInputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
